/*
 * @Author: CPS
 * @Date: 2020-07-21 21:21:47
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-31 11:51:11
 * @Projectname Electron-fileWatcher
 * @Filename watcher.js
 */
'use strict'
import fs from 'fs'
import chokidar from 'chokidar'

let defaultOptions = {
  persistent: true, // 进程保持

  ignored: ['*.txt', '*.cmd', '新建文件夹'], //忽略监测
  ignoreInitial: false, //是否跳过监听文件创建 （add/adddir)事件 默认否
  followSymlinks: true, //对链接是否进行深度监听（默认不进行）
  cwd: '.',
  disableGlobbing: false, //返回的path 使用str格式，与 glob对接更容易

  usePolling: false, //使用fs.stat 轮询监测（消耗cpu）不推荐(某些平台自动设置true)
  interval: 300, //轮询的监听间隔（开启 usePolling时才有效)
  binaryInterval: 300, //轮询的监听间隔（开启 usePolling时才有效)
  useFsEvents: true, // 默认true就行
  alwaysStat: false, //如果依赖FS，则推荐设置为true
  depth: 1, //设置一个子目录监听级别，不用每层子目录都监听(默认undefined)
  awaitWriteFinish: { //设置文件完全写入后再触发相对事件的范围（监听大文件常用）
    stabilityThreshold: 2000, //如果文件持续两秒大小没有改变，则发出事件
    pollInterval: 300 //监听的间隔
  },

  ignorePermissionErrors: false, //忽略没有监听权限的错误信息
  atomic: 200 //默认100毫秒，100毫秒内删除重新添加的文件，只会发出一个change事件
  //（默认值：如果useFsEvents和usePolling为false，则为true）。
  //自动过滤掉使用“原子写入”而不是直接写入源文件的编辑器时出现的工件。
  //如果文件在被删除后100毫秒内被重新添加，Chokidar将发出一个更改事件
  //而不是取消链接然后添加。如果默认值100毫秒对您不起作用，
  //您可以通过将atomic设置为自定义值（以毫秒为单位）来覆盖它。
}

/* 监听文件夹 */
function folderWatch(tarPath, listener) {
  let watcher
  if (!fs.lstatSync(tarPath)) return
  let fileList = fs.readdirSync(tarPath)

  // console.log('当前监听目录:' + tarPath)
  watcher = chokidar.watch(tarPath, defaultOptions)
    .on('ready', () => {
      console.log('文件夹已经准备好')
      if (!listener) return
      for (let each in listener) {
        console.log(each + ' 添加监听器.')
        watcher.on(each, listener[each])
      }
    })
  // .on('error', error => log(`Watcher error: ${error}`))
  // .on('add', path => log(`File ${path} has been added`))
  //   .on('change', path => log(`File ${path} has been changed`))
  //   .on('unlink', path => log(`File ${path} has been removed`));

  // watcher
  //   .on('addDir', path => log(`Directory ${path} has been added`))
  //   .on('unlinkDir', path => log(`Directory ${path} has been removed`))
  //   .on('ready', () => log('Initial scan complete. Ready for changes'))
  // .on('raw', (event, path, details) => { // internal
  //   log('Raw event info:', event, path, details);
  // });
  return watcher
}

if (require.main === module) {
  const path = require('path')
  let p = 'D:\\CPS\\MyProject\\Electron-fileWatcher\\design\\resource\\2020年\\7月'
  let P = 'D:\\CPS\\MyProject\\Electron-fileWatcher\\design\\resource\\2020年\\7月\\vvvb.xlsx'
  let w = folderWatch(p)

  console.log(path.basename(path.dirname(p)))
  console.log(path.basename(path.dirname(p)))
}

export default folderWatch
